import java.util.PriorityQueue;

public class Solution215 {
    public int findKthLargest(int[] nums, int k) {
        /**
         * 利用heap
         * 1. 维护一个size为K的 min heap
         * 2. 如果堆新的元素比堆顶大就压入堆中
         */
        //优先队列
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
        for (int num : nums) {
            if (minHeap.size() <= k || minHeap.peek() < num) {
//                minHeap.add(num);
                minHeap.offer(num);
            }
            if (minHeap.size() > k) {
                minHeap.poll();
            }
        }
        return minHeap.peek();
    }

    public static void main(String[] args) {
        int[] nums = {2, 1};
        int kthLargest = new Solution215().findKthLargest(nums, 2);
        System.out.println(kthLargest);
    }
}
